import dataPreferences from '@ohos.data.preferences'

class PreferencesUtil {
  prefMap: Map<string, dataPreferences.Preferences> = new Map()
  tag: string = 'PreferencesUtil'

  async loadPreferences(context, name: string) {
    //异步写法
    // preferences.getPreferences(context,name)
    //   .then(pref=>{
    //     this.prefMap.set(name,pref)
    //   })
    //   .catch(reason=>{
    //     console.log(this.tag,`加载getPreferences失败${name}`,JSON.stringify(reason))
    //   })

    //同步写法
    try {
      let pref = await dataPreferences.getPreferences(context, name)
      this.prefMap.set(name, pref)
    } catch (reason) {
      console.log(this.tag, `加载getPreferences失败${name}`, JSON.stringify(reason))
    }
  }

  async putPreferenceValue(name: string, key: string, value: dataPreferences.ValueType) {
    if (!this.prefMap.has(name)) {
      console.log(this.tag, `pref${name}初始化失败`)
      return
    }
    let pref = this.prefMap.get(name)
    try {
      await pref.put(key, value);
      await pref.flush();
    }catch (e){
      console.log(this.tag, `存入失败`);
    }

  }

  async getPreferenceValue(name: string, key: string, defaultValue: dataPreferences.ValueType) {
    if (!this.prefMap.has(name)) {
      console.log(this.tag, `pref${name}初始化失败`)
      return
    }

    try {
      let pref = this.prefMap.get(name)
      let x = await pref.get(key, defaultValue);
      return x
    }catch (e){
      console.log(this.tag, `获取失败`);
    }

  }

  async deletePreference(name: string, key: string) {
    if (!this.prefMap.has(name)) {
      console.log(this.tag, `pref${name}初始化失败`)
      return
    }
    let pref = this.prefMap.get(name)
    return await pref.delete(key);
  }
}

const preferencesUtil = new PreferencesUtil()

export default preferencesUtil as PreferencesUtil